//
//  TIpInfoDetailViewController.m
//  TipsProject
//
//  Created by Suny on 15/5/23.
//  Copyright (c) 2015年 Suny. All rights reserved.
//

#import "TipInfoDetailViewController.h"
#import "TipInfo.h"
#import "MGScrollView.h"
#import "MGBox.h"
#import "UIBarButtonItem+BaseFramework.h"
#import "TipItemView.h"
#import "TipBaseInfoView.h"
#import "LastTipItemView.h"
#import "TipsService.h"
#import "TipCommentViewController.h"


#define kPageCountViewHeight 40
@interface TipInfoDetailViewController()<UIScrollViewDelegate>
@property (nonatomic, strong) MGBox *photosGrid;
@property (nonatomic, strong) TipsService *tipService;

@property (nonatomic, strong)UIImageView *leftArrowImageView;
@property (nonatomic, strong)UIImageView *rightArrowImageView;
@property (nonatomic, strong)UIView *pagePannel;

@property (nonatomic, strong)UILabel *pageLabel;

@end
@implementation TipInfoDetailViewController


- (TipsService *)tipService
{
	if (!_tipService)
 {
		_tipService = [[TipsService alloc] initDefaultBaseUrlString];
	}
	return _tipService;
}
- (id)init
{
	self = [super init];
	if (self)
	{
		self.hasNavigationBar = YES;
	}
	return self;
}

- (MGScrollView *)scroller
{
	if (!_scroller)
	{
		_scroller = [MGScrollView scroller];
		_scroller.pagingEnabled = YES;
		_scroller.delegate = self;
		_scroller.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"tip_detail_background"]];
		_scroller.showsHorizontalScrollIndicator = NO;
		
		self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"tip_detail_background"]];

	}
	
	return _scroller;
}


- (TipInfo *)tipInfo
{
	if (!_tipInfo)
	{
		_tipInfo = [[TipInfo alloc]init];
	}
	
	return _tipInfo;
}

- (void)viewDidLoad
{
	[super viewDidLoad];


    self.navigationItem.leftBarButtonItem = self.defaultBackButtonItem;

    if (self.isPreviewMode)
    {
        self.navigationItem.rightBarButtonItem = [UIBarButtonItem rightBarButtonItemWithTitle:@"发布"
                                                                                       target:self
                                                                                     selector:@selector(handlePreviewClick)];

		[self setNavigationTitle:@"预览"];

		[self loadTipInfoData];
    }
    else
    {
		[self setNavigationTitle:@"技巧"];

    }
	

    
}


- (void)viewWillAppear:(BOOL)animated
{
	if (self.isFirstAppear && !self.isPreviewMode)
	{
		[self requestDataFromNet];
	}
}

- (void)loadTipInfoData
{
	self.scroller.frame = CGRectMake(0,
									 self.navigationBarHeight,
									 self.view.width,
									 self.view.height - self.navigationBarHeight - kPageCountViewHeight);

	[self.view addSubview:self.scroller];
	
	// the photos grid
	_photosGrid = [MGBox boxWithSize:[self pageSize]];
	_photosGrid.contentLayoutMode = MGLayoutStackVerticalWithWrap;
	
	[self.scroller.boxes addObject:_photosGrid];
	
	TipBaseInfoView *baseView = [TipBaseInfoView tipBaseInfoViewWithTipInfo:self.tipInfo
																   withSize:[self pageSize]];
	
	
	baseView.backgroundColor = [UIColor colorWithHexString:@"e1e1e1"];
	
	[baseView setPadding:UIEdgeInsetsZero];
	
	[baseView setMargin:UIEdgeInsetsMake(5,
											5,
											5,
											5)];
	baseView.toolBarDelegate = self;
	
	[_photosGrid.boxes addObject:baseView];
	
	for (int i = 0; i < self.tipInfo.fileArray.count; i++)
	{
		TipItem *tipItem = [self.tipInfo.fileArray safeObjectAtIndex:i];
		[_photosGrid.boxes addObject:[self createPageWithTipItem:tipItem]];
	}
	
	
//	LastTipItemView *lastTipItemView = [LastTipItemView itemWithTipInfo:self.tipInfo
//															   withSize:[self pageSize]];
//    [lastTipItemView setMargin:UIEdgeInsetsMake(5,
//                                         5,
//                                         5,
//                                         5)];
//	
//	[_photosGrid.boxes addObject:lastTipItemView];
//	
	// add a blank "add photo" box
	
	[_photosGrid layoutWithSpeed:0.3 completion:nil];
	[self.scroller layoutWithSpeed:0.3 completion:nil];
	
	
	[self.pagePannel addSubview:self.leftArrowImageView];
	
	[self.pagePannel addSubview:self.pageLabel];
	self.pageLabel.text = [NSString stringWithFormat:@"1/%ld",[self.tipInfo.attachmentNum integerValue] + 1];
	self.pageLabel.centerY = self.pagePannel.height/2;
	self.leftArrowImageView.left = 10;
	[self.pagePannel addSubview:self.rightArrowImageView];
	self.pagePannel.backgroundColor = [UIColor clearColor];
	
	
	[self.view addSubview:self.pagePannel];
}

- (UIView *)pagePannel
{
	if (!_pagePannel)
	{
		UIView *view = [[ UIView alloc] initWithFrame:CGRectMake(0, 
																 self.scroller.bottom,
																 self.view.width, 
																 kPageCountViewHeight)];
		
		_pagePannel = view;
	}
	
	return _pagePannel;
}

- (UILabel *)pageLabel
{
	if (!_pageLabel) 
	{
		_pageLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.pagePannel.width - 100 - self.rightArrowImageView.left,
															   0,
															   100, 30)];
		_pageLabel.textAlignment = NSTextAlignmentRight;
		_pageLabel.font = [UIFont systemFontOfSize:14];
		_pageLabel.backgroundColor = [UIColor clearColor];
		_pageLabel.right = self.rightArrowImageView.left;
		
	}
	return _pageLabel;
}

- (UIImageView *)leftArrowImageView
{
	if (!_leftArrowImageView)
	{
		UIImageView *leftArrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrowLeft.png"]];
		leftArrow.left = 10;
		leftArrow.centerY = self.pagePannel.height /2.0;

		_leftArrowImageView = leftArrow;
	}
	
	return _leftArrowImageView;
}

- (UIImageView *)rightArrowImageView
{
	if(!_rightArrowImageView)
	{
		UIImageView *rightArrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrowRight.png"]];
		rightArrow.right = self.pagePannel.width - 10;
		rightArrow.centerY = self.pagePannel.height /2.0;
			
		_rightArrowImageView = rightArrow;
	}
	return _rightArrowImageView;
}

- (void)requestDataFromNet
{
	[self.coverView startAnimating];
	WEAKSELF
	[self.tipService getTipDetailByTipId:self.tipInfo.tipId
							 finishBlock:^(BaseResponse *response) {
								 
								 [weakSelf handleGetTipDetailResponse:response];
							 }];
	
}

- (void)handleGetTipDetailResponse:(BaseResponse *)response
{
	[self.coverView stopAnimating];
	if (response.success)
	{
		if ([response.object isKindOfClass:[TipInfo class]])
		{
			self.tipInfo = response.object;
			
			[self loadTipInfoData];
		}
		else
		{
			[self showErrorMessage:Data_Error];
			[self.coverView stopAnimationWithRetryAction:@selector(requestDataFromNet) withActObject:self];

		}
	}
	else
	{
		if (response.httpResponseCode == 200)
		{
			[self showErrorMessage:Data_Error];
		}
		else
		{
			[self showErrorMessage:NetWork_NotReachable];
		}
		
		[self.coverView stopAnimationWithRetryAction:@selector(requestDataFromNet) withActObject:self];
	}
	
}

- (void)handlePreviewClick
{
	[self showHandleDataDefaultMessage];
	WEAKSELF
	[self.tipService publishTipToServe:self.tipInfo finishBlock:^(BaseResponse *response) {
		STRONGSELF
		if (response.success)
		{
			[strongSelf showHandleDataCompleteDefaultMessage];
			[strongSelf.navigationController dismissViewControllerAnimated:YES completion:nil];
		}
		else
		{
			if (response.httpResponseCode == 200)
			{
				[strongSelf showErrorMessage:response.desc];
			}
			else
			{
				[strongSelf showErrorMessage:NetWork_NotReachable];
			}
		}
	}];
}


- (CGSize)pageSize
{
	return (CGSize){self.scroller.width - 10 ,self.scroller.height - 10};
}


- (TipItemView *)createPageWithTipItem:(TipItem *)tipItem
{
    TipItemView *tipItemView = [TipItemView tipItemViewWithTipItem:tipItem
                                                          withSize:[self pageSize]];
	
	[tipItemView setPadding:UIEdgeInsetsZero];

    [tipItemView setMargin:UIEdgeInsetsMake(5,
                                            5,
                                            5,
                                            5)];


    return tipItemView;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
	NSInteger currentPage = ceilf(scrollView.contentOffset.x /scrollView.width) + 1;
	NSInteger maxPage = ceilf(scrollView.contentSize.width /scrollView.width);
	
	currentPage = currentPage >= maxPage ? maxPage :currentPage;
	
	self.pageLabel.text = [NSString stringWithFormat:@"%ld/%ld",(long)currentPage,[self.tipInfo.attachmentNum integerValue] + 1];

}


- (void)tipInfoToolBar:(TipInfoToolBar *)toolBar clickView:(TipInfoToolBarItem *)item
{
	WEAKSELF
	if (item.tag == TipInfoToolBarItemTagCommon)
	{
		TipCommentViewController *commentViewController = [[TipCommentViewController alloc] initWithTipInfo:self.tipInfo];
		
		[[AppDelegate rootNavigationController] pushViewController:commentViewController
														  animated:YES];
	}
	else if (item.tag == TipInfoToolBarItemTagPrise)
	{
		[self.tipService priseTipsToServe:[LoginUserInfo sharedInstance].userId
									tipId:self.tipInfo.tipId
							  finishBlock:^(BaseResponse *response) {
								  if (response.success)
								  {
									  STRONGSELF
									  [strongSelf showProgressHUDCompleteMessage:@"处理成功！"];
									  
									  item.selected = !item.selected;
								  }
								  else 
								  {
									  STRONGSELF
									  if ([response.status isEqualToString:@"NotAllowRepeatAction"])
									  {
										  [strongSelf showAlertTip:response.desc];
									  }
									  else
									  {
										  [strongSelf showAlertTip:Data_Error];
									  }
								  } 
							  }];

	}
	else if (item.tag == TipInfoToolBarItemTagCollection)
	{
		[self.tipService collectionTipsToServe:[LoginUserInfo sharedInstance].userId
									tipId:self.tipInfo.tipId
							  finishBlock:^(BaseResponse *response) {
								  if (response.success)
								  {
									  STRONGSELF
									  [strongSelf showProgressHUDCompleteMessage:@"处理成功！"];
									  item.titleLabel.text = [NSString stringWithFormat:@"%ld",[item.titleLabel.text integerValue]+1];

									  item.userInteractionEnabled = NO;

								  }
								  else 
								  {
									  STRONGSELF
									  if ([response.status isEqualToString:@"NotAllowRepeatAction"])
									  {
										  [strongSelf showAlertTip:response.desc];
									  }
									  else
									  {
										  [strongSelf showAlertTip:Data_Error];
									  }
								  } 
							  }];
	}

}

@end
